package na.learn.java.sorting;

import java.util.Comparator;

public class SelectionSort {

	public static void sort(Object[] obj) {
		Comparator comparator;

		if (obj == null && (!(obj[0] instanceof Comparable))
				&& (!(obj[0] instanceof Sortable)))

			throw new IllegalArgumentException(
					"Object of thes type cannot be sorted.");
		else {
			if ((obj[0] instanceof Sortable)
					&& ((comparator = ((Sortable) obj[0]).getComparator()) != null)) {
				sortUsingComparator(obj, comparator);

			} else if (obj[0] instanceof Comparable) {
				sortUsingComparable(obj);

			}
		}

		return;
	}

	private static void sortUsingComparator(Object[] obj, Comparator comparator) {
		int smallest = 0;
		//Object smallest = obj[0];
		int length = obj.length;
		for (int count = 1; count < length; count++) {
			smallest = count -1;
			for (int innerCount = count; innerCount < length; innerCount++) {
				if ((comparator.compare(obj[smallest], obj[innerCount])) > 0)
					swap(obj, smallest, innerCount);
			}

		}

	}

	private static void swap(Object[] obj, int oldLoc, int newLoc) {
		Object tmp = obj[oldLoc];
		obj[oldLoc] = obj[newLoc];
		obj[newLoc] = tmp;
	}

	private static void sortUsingComparable(Object[] obj) {
		int smallest = 0;
		//Object smallest = obj[0];
		int length = obj.length;
		for (int count = 1; count < length; count++) {
			smallest = count -1;
			for (int innerCount = count; innerCount < length; innerCount++) {
				if ((((Comparable)obj[smallest]).compareTo((Comparable) obj[innerCount])) > 0)
					swap(obj, smallest, innerCount);
			}

		}

	}
}
